layui.config({
    base: CXL.ctxPath + '/externaljs/'
}).extend({ //设定组件别名
    echarts: 'echarts/echarts',
    axios: 'axios/axios'
});
layui.use(['table', 'laydate', 'echarts', 'axios'], function () {
    var admin = layui.admin;
    var table = layui.table;
    var laydate = layui.laydate;
    var $ = layui.$;
    //数据图的参数
    var faultData = null;
    var faultchart = document.getElementById('faultChart');
    var faultechart = null;
    var echarts = layui.echarts;
    var axios = layui.axios;

//执行方法
    initPage();


    //函数区域
    function initPage() {
        faultechart = echarts.init(faultchart);
        updateFaultChartData();
        $(document).ready(function () {
            faultechart.resize();
        })
        window.addEventListener("resize", function () {
            faultechart.resize();
        });
    }

    //更新图表数据

    /**
     *    更新图表数据
     */
    function updateFaultChartData(postData) {
        $.ajax({
            url: CXL.ctxPath + "/common/faultrecord/getFaulttypeAndCountByParams",
            type: "POST",
            data: postData,
            dataType: "json",
            success: function (res) {
                if (res.success) {
                    let sOption = getChartOption(res.obj);
                    faultechart.hideLoading();
                    faultechart.setOption(sOption, {notMerge: true});
                } else {
                    CXL.error(res.msg);
                }
            },
            fail: function () {
                CXL.error("网络错误！");
            }
        });

    }

    //获取图表参数
    function getChartOption(data) {
        //数据表参数
        let faultOption = {
            color: ['#1d9dff', '#006cff', '#60cda0', '#ed8884', '#8b78f6', '#3a91d2', '#06a0ab', '#86c9f4'],
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b} : {c} ({d}%)'
            },
            // legend: {
            //     left: 'center',
            //     top: 'bottom',
            //     data: ['小车变频故障', '大车变频故障', '小车热继故障', '大车热继故障', '起升变频故障', '抓斗钢丝绳脱槽故障','主起升重锤故障', '其它'],
            //     textStyle: {
            //         color: '#fff'
            //     }
            // },
            series: [
                {
                    name: '故障类型',
                    type: 'pie',
                    label: {
                        show: true,
                        color: (params) => {
                            var index = params.dataIndex;
                            return this.color[index];
                        },
                    },
                    emphasis: {
                        label: {
                            show: true,

                        }
                    },
                    data: data
                }
            ]
        };
        return faultOption;
    }

    /**
     * 表格参数
     */
    var Page = {
        tableId: 'fault-table',
        url: CXL.ctxPath + '/common/faultrecord/datagrid',
        toolbar: '#plan-toolbar',
        where: {field: 'meetTime', order: 'desc'},

        initColumn: function () {
            return [[
                {type: 'numbers'}
                , {field: 'craneId', title: '天车编号', width: 95}
                , {field: 'faultType', title: '故障类型', width: 140}
                , {
                    field: 'workMode', title: '工作模式', width: 95, templet: function (d) {
                        if (d.workMode == "automatic") {
                            res = "自动"
                        } else {
                            res = "手动"
                        }
                        return res;
                    }
                }
                , {
                    field: 'meetTime',
                    title: '发生时间',
                    width: 160,
                    templet: '<div>{{ layui.laytpl.toDateString(d.meetTime) }}</div>',
                }
                , {
                    field: 'additionInfo',
                    title: '备注',
                    width: 150,
                }
                ,{fixed: 'right', title:'操作', toolbar: '#fault-record-tool', width:75}
            ]];
        },
        editUrl:CXL.ctxPath + '/common/faultrecord/editAddition/'
    };


    /**
     * 页面查询
     */
    Page.searchAction = function () {
        let queryData = {};
        //查询字段
        queryData['craneId'] = $("#craneidinput").val();
        queryData['workMode'] = $("#workmodeinput").val();

        // queryData['meetTime_begin'] = $("#timeBegin").val();
        queryData['meetTime_begin'] = $("#timeBegin").val();
        queryData['meetTime_end'] = $("#timeEnd").val();
        // queryData['order'] = "desc";


        queryData['faultType'] = $("#fuzzyMappingInput").val();
        // //排序字段
        // queryData['field'] = 'endTime';
        // queryData['order'] = 'desc';
        console.log(queryData);

        let postData = {};
        postData['craneId'] = $("#craneidinput").val();
        postData['beginTime'] = $("#timeBegin").val();
        postData['endTime'] = $("#timeEnd").val();
        postData['workMode'] = $("#workmodeinput").val();
        postData['fuzzyMapper'] = $("#fuzzyMappingInput").val();
        updateFaultChartData(postData);
        // console.log(postData);
        table.reload(Page.tableId, {page: {curr: 1}, where: queryData});
    }


    /**
     * 页面查询条件的重置
     */
    Page.resetAction = function () {
        laydate.render({
            elem: '#timeBegin' //指定元素
            , type: 'datetime'
            , value: new Date(new Date().getTime() - 8 * 60 * 60 * 1000)
        });
        laydate.render({
            elem: '#timeEnd' //指定元素
            , type: 'datetime'
            , value: new Date()
        });
        $("#craneidinput").val(0);
        $("#tasktypeinput").val('');
        form.render();
        Page.searchAction();
    }


    /**
     * 表格的单击事件
     */
    Page.clickAction = function (obj) {

    }

    /**
     * 表格的双击事件
     */
    Page.doubleClickAction = function (obj) {

    }

    /**
     * 新增
     */
    Page.openAdd = function () {
        layer.open({
            type: 2,
            title: '新增',
            shadeClose: true,
            shade: 0.8,
            area: ['700px', '700px'],
            content: Page.addUrl,
            btn: ['确定', '取消'],
            yes: function (index, layero) {
                //点击确认触发 iframe 内容中的按钮提交
                var submit = layero.find('iframe').contents().find("#form-btn-save");
                submit.click();

                //刷新表格
                Page.searchAction();
            }
        });
    };

    /**
     * 编辑
     */
    Page.openEdit = function (data) {
        //console.log(data);
        layer.open({
            type : 2,
            title : '编辑',
            shadeClose : true,
            shade : 0.8,
            area: ['700px', '700px'],
            content : Page.editUrl + data.id,
            btn : [ '确定', '取消' ],
            yes : function(index, layero) {
                //点击确认触发 iframe 内容中的按钮提交
                var submit = layero.find('iframe').contents().find("#form-btn-save");
                submit.click();

                //刷新表格
                Page.searchAction();
            }
        });
    };

    /**
     * 查看
     */
    Page.openDetail = function (data) {
        var data = data.data;
        var layer = layui.layer;
        layer.open({
            type: 1,
            content: $('#openShowBox'),
            area: ['700px', '800px'], //宽高
            btn: ["确定"],
            success: function (index, layero) {

                table.render({
                    elem: '#openShowTaskDetails'
                    , height: 'full-140'
                    , page: true
                    , limit: 30
                    , autoSort: false
                    , url: Page.url + "/" + data.id
                    , page: true
                    , cols: [[ //表头
                        {field: 'id', title: 'ID', sort: true, fixed: 'left'}
                        , {
                            field: 'beginTime',
                            title: '开始时间',
                            width: 180,
                            templet: '<div>{{ layui.laytpl.toDateString(d.beginTime) }}</div>'
                        }
                        , {
                            field: 'endTime',
                            title: '完成时间',
                            width: 180,
                            templet: '<div>{{ layui.laytpl.toDateString(d.endTime) }}</div>'
                        }
                        , {field: 'materialId', title: '物料ID', width: 90}
                        , {field: 'materialName', title: '物料名称', width: 90}
                        , {field: 'weight', title: '重量', width: 90}
                    ]]
                });

            }
        });
    }

    /**
     * 查看
     */
    Page.createWork = function (data) {
        layer.confirm('是否创建该任务？', {icon: 3, title: '提示'}, function (index) {
            //do something
            $.ajax({
                url: Page.createWorkUrl + "?id=" + data.id,
                method: 'POST',
                dataType: 'JSON',
                success(res) {
                    if (res.success) {
                        layer.close(index);
                        layer.msg('创建成功', {icon: 1});
                        Page.resetAction();
                    } else {
                        layer.close(index);
                        layer.alert(res.msg, {icon: 2});
                    }
                }
            });
        });
    }


    /**
     * 表格渲染
     */
    table.render({
        elem: '#' + Page.tableId
        , url: Page.url
        , height: 'full-140'
        , page: true
        , limit: 30
        , autoSort: false
        , toolbar: Page.toolbar
        , where: Page.where
        , defaultToolbar: [],
        done: function (res, curr, count) {
            $("#total").html(count);
        }

        , cols: Page.initColumn()
    });

    /**
     * 表头工具栏
     */
    table.on('toolbar(' + Page.tableId + ')', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'doAdd':
                Page.openAdd();
                break;
        }
        ;
    });

    /**
     * 监听表格工具事件
     */
    table.on('tool(' + Page.tableId + ')', function (obj) {
        //获得当前行数据
        var data = obj.data;
        //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        var layEvent = obj.event;

        //查看操作
        if (layEvent === 'detail') {
            Page.openDetail(obj);
        }
        //删除操作
        else if (layEvent === 'del') {
            Page.deleteAction(obj);
        }
        //编辑操作
        else if (layEvent === 'edit') {
            Page.openEdit(data);
        } else if (layEvent === 'createWork') {
            Page.createWork(data);
        }
    });


    /**
     * 搜索按钮事件
     */
    $('#btnSearch').click(function () {
        Page.searchAction();
    });

    //导出按钮监听
    $('#exportRecord').click(function () {
        let postData = {};
        //查询字段
        postData['craneId'] = $("#craneidinput").val();
        postData['beginTime'] = $("#timeBegin").val();
        postData['endTime'] = $("#timeEnd").val();
        postData['workMode'] = $("#workmodeinput").val();
        postData['fuzzyMapper'] = $("#fuzzyMappingInput").val();


        var fileName = postData['craneId'] + "号天车故障记录" + postData['workMode'] + moment().format("h_mm_ss");
        $.ajax({
            url: CXL.ctxPath + "/common/faultrecord/exportFaultRecord",
            type: "POST",
            data: postData,
            dataType: "json",
            responseType: "arraybuffer",
            success: function (res) {
                if (res.success) {
                    let path = String(res.obj);
                    downloadFile(path);
                    CXL.success("成功！");

                } else {
                    CXL.error(res.msg);
                }
                // var n = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),
                //     i = fileName + ".xlsx",
                //     r = document.createElement("a");
                // r.href = URL.createObjectURL(n),
                //     r.download = i,
                //     document.body.appendChild(r),
                //     r.click(),
                //     window.setTimeout(function () {
                //         URL.revokeObjectURL(n), document.body.removeChild(r)
                //     }, 0);

            },
            fail: function () {
                CXL.error("网络错误！");
            }
        });
    });

    function downloadFile(filePath) {
        let param = new URLSearchParams()
        param.append('filePath', filePath);
        // param.append('pwd', 'admin')
        axios({
            url: CXL.ctxPath + "/common/faultrecord/download",
            method: 'post',
            responseType: 'blob',
            data: param
        })
            .then(res => {
                //文件名 文件保存对话框中的默认显示
                let fileName = new Date().toLocaleTimeString()+"导出记录.xlsx";
                let data = res.data;
                if (!data) {
                    return
                }
                console.log(res);
                //构造a标签 通过a标签来下载
                let url = window.URL.createObjectURL(new Blob([data]))
                let a = document.createElement('a')
                a.style.display = 'none'
                a.href = url
                //此处的download是a标签的内容，固定写法，不是后台api接口
                a.setAttribute('download', fileName)
                document.body.appendChild(a)
                //点击下载
                a.click()
                // 下载完成移除元素
                document.body.removeChild(a);
                // 释放掉blob对象
                window.URL.revokeObjectURL(url);
            })
            .catch(res => {
            })
    }


// //导出记录
// exportFile = function () {
//
//
// }

    /**
     * 搜索按钮事件
     */
    $('#btnReset').click(function () {
        Page.resetAction();
    });

//监听行单击事件
    table.on('row(' + Page.tableId + ')', function (obj) {
        Page.clickAction(obj);
    });

//监听行双击事件
    table.on('rowDouble(' + Page.tableId + ')', function (obj) {
        Page.doubleClickAction(obj);
    });

    /**
     * 时间选择器渲染
     * 开始时间
     */
    laydate.render({
        elem: '#timeBegin' //指定元素
        , type: 'datetime'
        , value: new Date(new Date().getTime() - 10000 * 60 * 60 * 1000)
    });

    /**
     * 时间选择器渲染
     * 结束时间
     */
    laydate.render({
        elem: '#timeEnd' //指定元素
        , type: 'datetime'
        , value: new Date()
    });

})
;
